<template>
  <view class="login">
    <navBar>
      <text class="reg">注册</text>
    </navBar>
    <view class="topBar">
      <view class="left">{{loginSwitch ? '短信验证码' : '密码'}}登录</view>
      <view class="right" v-on:click="loginSwitch = !loginSwitch">{{loginSwitch ? '密码' : '短信验证码'}}登录 <uni-icons type="right" size="15"></uni-icons></view>
    </view>
    <view class="form">
      <uni-forms ref="form" :modelValue="formData" :rules="loginSwitch ? codeRules : passwordRules">
        <uni-forms-item name="mobile">
          <view class="formsItem">
            <uni-easyinput type="text" v-model="formData.mobile":inputBorder="false" placeholder="请输入手机号" :clearable="false"/>
          </view>
        </uni-forms-item>
        <uni-forms-item name="code" v-if="loginSwitch">
          <view class="formsItem">
            <uni-easyinput type="text" v-model="formData.code" :inputBorder="false" placeholder="请输入验证码" :clearable="false"/>
            <view class="button" v-on:click="getCode" v-if="codeTime === 0">获取验证码</view>
            <view class="button" v-else>{{ codeTime < 10 ? '0' + codeTime : codeTime }}秒后再次发送</view>
          </view>
        </uni-forms-item>
        <uni-forms-item name="password" v-else>
          <view class="formsItem">
            <uni-easyinput type="password" v-model="formData.password" :inputBorder="false" placeholder="请输入密码" />
          </view>
        </uni-forms-item>
      </uni-forms>
      <view class="eula">
        <radio value="true" :checked="eulaOkay" v-on:click="eulaOkay = !eulaOkay" color="#16c2a3"/><text v-on:click="eulaOkay = !eulaOkay" >我已同意<text class="span">用户协议</text>及<text class="span">隐私条款</text></text>
      </view>
      <button v-on:click="loginFn">提 交</button>
      <text>忘记密码?</text>
    </view>
  </view>
</template>

<script>
  import loginNavBar from '@/components/loginNavBar/loginNavBar.vue'
  import { getCode, codeLogin, passwordLogin } from '@/api/login.js'
  export default {
    components: {
      navBar: loginNavBar
    },
    onReady() {
      this.$refs.form.setRules(this.passwordRules)
    },
    data() {
      return {
        loginSwitch: false,
        formData: {
          mobile: '',
          password: '',
          code: ''
        },
        passwordRules: {
          mobile: {
            rules: [{
              required: true,
              errorMessage: '请输入手机号'
            },{
              validateFunction:function(rule,value,data,callback){
                if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
                  callback('手机号格式错误')
                }
                return true
              }
            }]
          },
          password: {
            rules: [{
              required: true,
              errorMessage: '请输入密码'
            }]
          }
        },
        codeRules: {
          mobile: {
            rules: [{
              required: true,
              errorMessage: '请输入手机号'
            },{
              validateFunction:function(rule,value,data,callback){
                if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
                  callback('手机号格式错误')
                }
                return true
              }
            }]
          },
          code: {
            rules: [{
              required: true,
              errorMessage: '请输入验证码'
            },{
              validateFunction:function(rule,value,data,callback){
                if (value.lenth !== 6) {
                  callback('验证码长度必须为 6 个字符')
                }
                return true
              }
            }]
          }
        },
        mobileRules: {
          mobile: {
            rules: [{
              required: true,
              errorMessage: '请输入手机号'
            },{
              validateFunction:function(rule,value,data,callback){
                if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
                  callback('手机号格式错误')
                }
                return true
              }
            }]
          },
          code: {
            rules: [{
              required: false
            }]
          }
        },
        eulaOkay: false,
        codeTime: 0,
      };
    },
    methods: {
      setCodeTime(){
        if (this.codeTime > 0) {
          setTimeout(()=>{
            --this.codeTime
            this.setCodeTime()
          }, 1000)
        }
      },
      async getCode() {
        this.$refs.form.setRules(this.mobileRules)
        try{
          await this.$refs.form.validate()
          await getCode({
            mobile: this.formData.mobile,
            type: 'login'
          })
          this.codeTime = 60 // 设置超时时间
          this.setCodeTime()
        } catch (e) {
          console.log('err',e);
        } finally {
          this.$refs.form.setRules(this.codeRules)
        }
      },
      loginFn() {
        this.$refs.form.validate().then(async res => {
          // 是否同意条款
          if (!this.eulaOkay) {
            uni.showToast({
              title:'请同意协议与条款',
              icon: 'none'
            })
            return
          }
          // 接收返回值
          let response = []
          // 判断登录类型
          if (this.loginSwitch) {
            response = await codeLogin({
              mobile: this.formData.mobile,
              code: this.formData.code
            })
          } else {
            response = await passwordLogin({
              password: this.formData.password,
              mobile: this.formData.mobile
            })
          }
          console.log(response[1]);
          uni.setStorage({
            key: 'tokens',
            data: {
                token: response[1].data.token,
                refreshToken: response[1].data.refreshToken,
            },
            success: () => {
              this.$store.commit('setUser', {
                token: response[1].data.token,
                refreshToken: response[1].data.refreshToken,
              })
              uni.switchTab({
                url:'/pages/user/user'
              })
            }
          })
        }).catch(err =>{
          console.log('登录错误信息：', err);
        })
      }
    },
    watch: {
      loginSwitch(newVal) {
        this.eulaOkay = false
        if(newVal) {
          this.formData.password = ''
          this.$refs.form.setRules(this.codeRules)
        } else {
          this.formData.code = ''
          this.$refs.form.setRules(this.passwordRules)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.reg , .button{
  color: #16c2a3
}
.topBar {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding: 60rpx 60rpx 100rpx 60rpx;
  .left {
    font-size: 55rpx
  }
  .right {
    font-size: 30rpx
  }
}
.form {
  margin: 0 40rpx;
  .formsItem {
    display: flex;
    border-bottom: 1rpx solid #F0F1F4;
  }
  button {
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    margin: 40rpx 0;
    background-color: #16c2a3;
    color: #F0F1F4;
  }
  .eula {
    radio {
      transform: scale(.6);
    }
    .span {
      color: #16c2a3;
    }
  }
  text {
    font-size: 30rpx
  }
}
</style>
